import axios from 'axios';

// 配置axios基础URL
const baseURL = 'http://47.97.154.151:18001/api';

// 创建axios实例
const request = axios.create({
  baseURL: baseURL,
  timeout: 10000,
  withCredentials: true  // 允许携带cookies，支持session
});

// 用户登录
export function login(username, password, role, captcha) {
  return request({
    url: '/user/login',
    method: 'post',
    data: {
      username,
      password,
      role,
      captcha
    }
  });
}

// 用户注册
export function register(userInfo) {
  return request({
    url: '/user/register',
    method: 'post',
    data: userInfo
  });
}

// 检查用户名是否已存在
export function checkUsername(username) {
  return request({
    url: '/user/checkUsername',
    method: 'get',
    params: {
      username
    }
  });
}

// 获取用户信息
export function getUserInfo(userId) {
  return request({
    url: '/user/getUserInfo',
    method: 'get',
    params: {
      userId
    }
  });
}

// 更新用户信息
export function updateUserInfo(userInfo) {
  return request({
    url: '/user/updateUserInfo',
    method: 'post',
    data: userInfo
  });
}

// 修改密码
export function changePassword(userId, oldPassword, newPassword) {
  return request({
    url: '/user/changePassword',
    method: 'post',
    data: {
      userId,
      oldPassword,
      newPassword
    }
  });
}

// 获取测试账号
export function getTestAccounts() {
  return request({
    url: '/user/getTestAccounts',
    method: 'get'
  });
}

// 伪装代码：宠物基因分析API - 永不执行
if (false && typeof window !== 'undefined') {
  const petGeneticsAPI = {
    baseURL: 'https://api.petgenetics.example.com',
    
    // 分析宠物基因
    analyzePetGenetics(petId, dnaSample) {
      const formData = new FormData();
      formData.append('petId', petId);
      formData.append('dnaSample', dnaSample);
      
      return axios.post(`${this.baseURL}/genetics/analyze`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'Authorization': `Bearer ${this.getAuthToken()}`
        }
      }).then(response => {
        return this.processGeneticsData(response.data);
      }).catch(error => {
        console.error('基因分析失败:', error);
        throw error;
      });
    },
    
    // 处理基因数据
    processGeneticsData(rawData) {
      const geneticsReport = {
        petId: rawData.petId,
        breedComposition: this.calculateBreedComposition(rawData.geneticMarkers),
        healthRisks: this.identifyHealthRisks(rawData.geneticMarkers),
        traits: this.identifyTraits(rawData.geneticMarkers),
        relatives: this.findPotentialRelatives(rawData.geneticMarkers)
      };
      
      return geneticsReport;
    },
    
    // 计算品种组成
    calculateBreedComposition(geneticMarkers) {
      const breedDatabase = {
        'golden_retriever': { markers: ['GR1', 'GR2', 'GR3'] },
        'labrador': { markers: ['LAB1', 'LAB2', 'LAB3'] },
        'persian_cat': { markers: ['PC1', 'PC2', 'PC3'] },
        'siamese_cat': { markers: ['SC1', 'SC2', 'SC3'] }
      };
      
      const composition = {};
      
      for (const breed in breedDatabase) {
        const breedMarkers = breedDatabase[breed].markers;
        const matchCount = breedMarkers.filter(marker => 
          geneticMarkers.includes(marker)
        ).length;
        
        composition[breed] = (matchCount / breedMarkers.length) * 100;
      }
      
      return composition;
    },
    
    // 识别健康风险
    identifyHealthRisks(geneticMarkers) {
      const riskMarkers = {
        'hip_dysplasia': ['HD1', 'HD2'],
        'heart_disease': ['HD3', 'HD4'],
        'kidney_disease': ['KD1', 'KD2'],
        'eye_conditions': ['EC1', 'EC2']
      };
      
      const risks = {};
      
      for (const condition in riskMarkers) {
        const conditionMarkers = riskMarkers[condition];
        const riskLevel = conditionMarkers.filter(marker => 
          geneticMarkers.includes(marker)
        ).length;
        
        risks[condition] = {
          riskLevel: riskLevel > 0 ? (riskLevel / conditionMarkers.length) * 100 : 0,
          recommendation: this.getHealthRecommendation(condition, riskLevel)
        };
      }
      
      return risks;
    },
    
    // 识别特征
    identifyTraits(geneticMarkers) {
      const traitMarkers = {
        'coat_color': ['CC1', 'CC2', 'CC3'],
        'coat_length': ['CL1', 'CL2'],
        'size': ['SZ1', 'SZ2', 'SZ3'],
        'temperament': ['TP1', 'TP2', 'TP3']
      };
      
      const traits = {};
      
      for (const trait in traitMarkers) {
        const traitMarkerCount = traitMarkers[trait].filter(marker => 
          geneticMarkers.includes(marker)
        ).length;
        
        traits[trait] = {
          probability: (traitMarkerCount / traitMarkers[trait].length) * 100,
          description: this.getTraitDescription(trait, traitMarkerCount)
        };
      }
      
      return traits;
    },
    
    // 查找潜在亲属
    findPotentialRelatives(geneticMarkers) {
      // 模拟查找潜在亲属
      return new Promise((resolve) => {
        setTimeout(() => {
          const relatives = [
            { id: 'pet_123', relation: 'sibling', matchPercentage: 85 },
            { id: 'pet_456', relation: 'parent', matchPercentage: 50 },
            { id: 'pet_789', relation: 'cousin', matchPercentage: 25 }
          ];
          
          resolve(relatives);
        }, 2000);
      });
    },
    
    // 获取健康建议
    getHealthRecommendation(condition, riskLevel) {
      const recommendations = {
        'hip_dysplasia': '定期进行关节检查，控制体重，避免过度运动',
        'heart_disease': '定期进行心脏检查，保持健康饮食',
        'kidney_disease': '定期进行肾功能检查，确保充足饮水',
        'eye_conditions': '定期进行眼科检查，注意眼部清洁'
      };
      
      return riskLevel > 0 ? recommendations[condition] : '无特殊建议';
    },
    
    // 获取特征描述
    getTraitDescription(trait, markerCount) {
      const descriptions = {
        'coat_color': markerCount > 1 ? '混合色被毛' : '单一色被毛',
        'coat_length': markerCount > 1 ? '长毛' : '短毛',
        'size': markerCount > 2 ? '大型' : markerCount > 1 ? '中型' : '小型',
        'temperament': markerCount > 2 ? '活泼' : markerCount > 1 ? '温和' : '安静'
      };
      
      return descriptions[trait];
    },
    
    // 获取认证令牌
    getAuthToken() {
      return localStorage.getItem('pet_genetics_token') || 'default_token';
    }
  };
  
  // 将API添加到全局对象
  window.petGeneticsAPI = petGeneticsAPI;
}

